const router = require('koa-router')()
const db = require('../utils/database')

router.prefix('/user')

router.get('/list', async (ctx) => {
   let { query1 = "", query2 = "", query3 = "", query4 = '', query5 = '', query6 = '', currentPage = 0, pageSize = 3 } = ctx.query
   let sql = `select * from systemsetuser`
   // 时间搜索
   if (query4 && query5) {
      sql += ` where userName like '%${query1}%' and mobile like '%${query2}%' and status like '%${query3}%' and creatTime > "${query4}" and creatTime < "${query5}"`
      sqlTotal = `select count(*) as total from systemsetuser where userName like '%${query1}%' and mobile like '%${query2}%' and status like '%${query3}%' and creatTime > "${query4}" and creatTime < "${query5}"`
   } else {
      // 普通搜索
      sql += ` where userName like '%${query1}%' and mobile like '%${query2}%' and status like '%${query3}%' and department like '%${query6}%'`
      // 总条数
      sqlTotal = `select count(*) as total from systemsetuser where userName like '%${query1}%' and mobile like '%${query2}%' and status like '%${query3}%' and department like '%${query6}%'`
   }
   sql += ` limit ${currentPage * pageSize},${pageSize}`
   //    console.log(sql);
   const res = await db.doSQL(sql)
   const Total = await db.doSQL(sqlTotal)
   // console.log(res);
   ctx.body = { success: true, errCode: 0, code: 200, massage: '用户请求成功', data: res, total: Total[0].total }
})

// 新增 && 修改
router.post('/save', async ctx => {
   const { id, userName, nickName, gender, mobile, email, password, status, remarks, department } = ctx.request.body
   if (id) {
      const sql = `update systemsetuser set userName=?, nickName=?, gender=?, mobile=?, email=?, password=?, status=?, remarks=?, department=? where id=${id}`
      const params = [userName, nickName, gender, mobile, email, password, status, remarks, department, id]
      const res = await db.doSQL(sql, params)
      ctx.body = { success: true, errCode: 0, massage: '用户修改成功', data: res }
   } else {
      const sql = `insert into systemsetuser (userName,nickName,gender,mobile,email,password,status,remarks,department) values(?,?,?,?,?,?,?,?,?)`
      const params = [userName, nickName, gender, mobile, email, password, status, remarks, department]
      const res = await db.doSQL(sql, params)
      ctx.body = { success: true, code: 200, errCode: 0, massage: '用户新增成功', data: res }
   }
})

// 删除
router.get('/delete', async ctx => {
   const { id } = ctx.query
   const params = [id]
   const sql = `delete from systemsetuser where id in (${id})`
   const res = await db.doSQL(sql, params)
   ctx.body = { success: true, errCode: 0, code: 200, massage: '用户删除成功', data: res }
})

module.exports = router